<?php
require_once( dirname(__FILE__).'/../libs/bedmintonlib.php' );

function changePassword( $emailAddress, $oldPassword, $newPassword, & $outMessage )
{
    $passwordSalt = "";
    $passwordHash = "";
    PasswordHash::hashPassword( $newPassword, $passwordSalt, $passwordHash );

    $db = Db::db();
    $dbConnection = $db->connection();
    if (is_null( $dbConnection ))
    {
        $outMessage = $db->getErrorStr();
        return false;
    }

    try
    {
        $statement = $dbConnection->prepare( "UPDATE customers SET passwordhash = ?, passwordsalt = ?, passwordtochange = NULL WHERE emailaddress = ? AND passwordtochange = ?" );
        $statement->bindParam( 1, $passwordHash, PDO::PARAM_STR );
        $statement->bindParam( 2, $passwordSalt, PDO::PARAM_STR );
        $statement->bindParam( 3, $emailAddress, PDO::PARAM_STR );
        $statement->bindParam( 4, $oldPassword, PDO::PARAM_STR );
        if (! $statement->execute())
        {
            $outMessage = isEnglish() ? "Execute error" : "Chyba pri vykonávaní príkazu";
            return false;
        }

        $db->commit();
    } 
    catch (PDOException $e)
    {
        $outMessage = $e->getMessage();
        return false;
    }
    
    WebStat::logPasswordChanged( $emailAddress );
    return true;
}

if (! isset( $_POST['emailaddress'] ) ||
    ! isset( $_POST['oldpassword'] ) ||
    ! isset( $_POST['newpassword'] ) ||
    ! isset( $_POST['confirmnewpassword'] ))
{
    showError( isEnglish() ? "Invalid data" : "Nesprávne dáta" );
    exit;
}

$emailAddress = $_POST['emailaddress'];
$oldPassword = $_POST['oldpassword'];
$newPassword = $_POST['newpassword'];
$confirmNewPassword = $_POST['confirmnewpassword'];

if ($newPassword != $confirmNewPassword)
{
    showError( isEnglish() ? "New and confirm new password aren't the same" : "Nové heslo a jeho potvrdenie sa nezhodujú" );
    exit;
}

$echoStr = "";
if (changePassword( $emailAddress, $oldPassword, $newPassword, $echoStr ))
{
    showInfo( isEnglish() ? "Your password was successfully changed" : "Vaše heslo bolo úspešne zmenené" );
    exit;
}

showError( $echoStr );

?>
